package com.cxria.shiro.shiro.filter;

import com.cxria.shiro.dto.ShiroStatus;
import com.cxria.shiro.enums.ShiroStatusCodeEnum;
import com.cxria.shiro.enums.ShiroStatusMsgEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class JsonResultRolesAuthorizationFilter extends RolesAuthorizationFilter {

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {
			saveRequestAndRedirectToLogin(request, response);
		} else {
			response.setContentType("application/json;charset=UTF-8");
			ShiroStatus status = new ShiroStatus(ShiroStatus.ERROR, ShiroStatusCodeEnum.USER_ROLE_ERROR, ShiroStatusMsgEnum.USER_ROLE_ERROR);
			response.getWriter().append(objectMapper.writeValueAsString(status));
		}
		return false;
	}

}
